﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SeDuce.Model;
using SeDuce.BLL;
using SeDuce.Utility;
using System.IO;

public partial class Management_Products_Add : PageBase
{
    List<Product> products = new List<Product>();

    Lazy_Yu<ProductBLL> lazyProductBLL = new Lazy_Yu<ProductBLL>(() => new ProductBLL());
    public ProductBLL LazyProductBLL
    {
        get { return this.lazyProductBLL.Value; }
    }
    Lazy_Yu<BrandBLL> lazyBrandBLL = new Lazy_Yu<BrandBLL>(() => new BrandBLL());
    public BrandBLL LazyBrandBLL
    {
        get { return this.lazyBrandBLL.Value; }
    }
    Lazy_Yu<TypeBLL> lazyTypeBLL = new Lazy_Yu<TypeBLL>(() => new TypeBLL());
    public TypeBLL LazyTypeBLL
    {
        get { return this.lazyTypeBLL.Value; }
    }
    Lazy_Yu<SizeBLL> lazySizeBLL = new Lazy_Yu<SizeBLL>(() => new SizeBLL());
    public SizeBLL LazySizeBLL
    {
        get { return this.lazySizeBLL.Value; }
    }
    Lazy_Yu<ColorBLL> lazyColorBLL = new Lazy_Yu<ColorBLL>(() => new ColorBLL());
    public ColorBLL LazyColorBLL
    {
        get { return this.lazyColorBLL.Value; }
    }

    

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.chklBrands.DataSource = this.LazyBrandBLL.GetBrands();
            this.chklBrands.DataTextField = "BrandName";
            this.chklBrands.DataValueField = "BrandID";
            this.chklBrands.DataBind();
            this.chklTypes.DataSource = this.LazyTypeBLL.GetTypes().ToList<SeDuce.Model.Type>().OrderBy(t => t.Sort);
            this.chklTypes.DataTextField = "TypeName";
            this.chklTypes.DataValueField = "TypeID";
            this.chklTypes.DataBind();
            this.cnklSizes.DataSource = this.LazySizeBLL.GetSizes().ToList<SeDuce.Model.Size>().OrderBy(t => t.Sort);
            this.cnklSizes.DataTextField = "SizeName";
            this.cnklSizes.DataValueField = "SizeID";
            this.cnklSizes.DataBind();
            this.cnklColors.DataSource = this.LazyColorBLL.GetColor();
            this.cnklColors.DataTextField = "ColorName";
            this.cnklColors.DataValueField = "ColorID";
            this.cnklColors.DataBind();
            this.rbtnlStatus.DataSource = new Utils().productStatus;
            this.rbtnlStatus.DataTextField = "Name";
            this.rbtnlStatus.DataValueField = "ID";
            this.rbtnlStatus.DataBind();
            this.rbtnlStatus.Items[0].Selected = true;
        }
    }
    protected void lbtnSave_Click(object sender, EventArgs e)
    {
        if (Session["file_info"] != null)
        {
            List<string> file_list_to_delete = new List<string>();
            try
            {
                List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;
                ImageHelp imgHelper = new ImageHelp();

                string UploadPath = Server.MapPath(Misc.product_filepath);
                if (!System.IO.Directory.Exists(UploadPath))
                {
                    System.IO.Directory.CreateDirectory(UploadPath);
                }

                foreach (Thumbnail img in thumbnails)
                {
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Replace("-", "");
                    string fullfilename = filename +Path.GetExtension(img.ID).ToLower();
                    string fullfilename_174 = filename + "_174_174" + Path.GetExtension(img.ID).ToLower();
                    string fullfilename_100 = filename + "_100_100" + Path.GetExtension(img.ID).ToLower();
                    file_list_to_delete.Add(Misc.product_filepath + "/" + fullfilename);
                    file_list_to_delete.Add(Misc.product_filepath + "/Temp_" + fullfilename);
                    file_list_to_delete.Add(Misc.product_filepath + "/Temp_Watermark_" + fullfilename);
                    FileStream fs = new FileStream(UploadPath + "\\Temp_" + fullfilename, FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(img.Data);
                    bw.Close();
                    fs.Close();

                    //watermark
                    Utils.Watermark(UploadPath + "\\Temp_" + fullfilename, UploadPath + "\\Temp_Watermark_" + fullfilename, Server.MapPath(Misc.watermark2), "CENTER");
                    Utils.Watermark(UploadPath + "\\Temp_Watermark_" + fullfilename, UploadPath + "\\" + fullfilename, Server.MapPath(Misc.watermark1), "BR");

                    file_list_to_delete.Add(Misc.product_filepath + "/" + fullfilename_174);
                    file_list_to_delete.Add(Misc.product_filepath + "/" + fullfilename_100);
                    imgHelper.GetSmaller(UploadPath + "\\" + fullfilename, UploadPath + "/" + filename, 174, 174);
                    imgHelper.GetSmaller(UploadPath + "\\" + fullfilename, UploadPath + "/" + filename, 100, 100);

                    products.Add(new Product()
                    {
                        ProductName = this.txtName.Text.Trim(),
                        UnitPrice = string.IsNullOrEmpty(this.txtUnitPrice.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text.Trim()),
                        SalePrice = this.txtSalePrice.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePrice.Text.Trim()) : 0,
                        Size = String.Join(",", (from item in cnklSizes.Items.Cast<ListItem>() where item.Selected select item.Text).ToArray<string>()),
                        Color = String.Join(",", (from item in cnklColors.Items.Cast<ListItem>() where item.Selected select item.Text).ToArray<string>()),
                        Description = this.txtDescription.Text.Trim(),
                        Date = DateTime.Now,
                        Status = this.rbtnlStatus.SelectedValue.ToInt(),
                        ImageBig = Misc.product_filepath + "/" + fullfilename,
                        Image174 = Misc.product_filepath + "/" + fullfilename_174,
                        Image100 = Misc.product_filepath + "/" + fullfilename_100,
                        UnitPriceUS = string.IsNullOrEmpty(this.txtUnitPriceUS.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPriceUS.Text.Trim()),
                        SalePriceUS = this.txtSalePriceUS.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePriceUS.Text.Trim()) : 0,
                        UnitPriceJP = string.IsNullOrEmpty(this.txtUnitPriceJP.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPriceJP.Text.Trim()),
                        SalePriceJP = this.txtSalePriceJP.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePriceJP.Text.Trim()) : 0,
                        Seq = this.ddlSeq.SelectedValue.ToInt()
                    });
                }
                object pid = this.LazyProductBLL.InsertProduct(products[0], 
                                                                (from item in chklBrands.Items.Cast<ListItem>() where item.Selected select item.Value.ToInt()).ToList<int>(),
                                                                (from item in chklTypes.Items.Cast<ListItem>() where item.Selected select item.Value.ToInt()).ToList<int>());
                if (pid != null)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key1", "javascript:" + string.Format("alert('{0}');window.location.href='PicList.aspx?ProductID={1}';", "操作成功!", Convert.ToInt32(pid)), true);
                }
                else
                {
                    throw new Exception("保存时发生错误");
                }
            }
            catch (Exception ex)
            {
                foreach (string file in file_list_to_delete)
                {
                    if (File.Exists(Server.MapPath(file)))
                    {
                        File.Delete(Server.MapPath(file));
                    }
                }
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key2", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
            }
            finally
            {
                Session.Remove("file_info");
            }
        }
    }
    protected void lbtnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("List.aspx");
    }
}